package com.b2c.repository.bd;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.bd.KeywordHotEntity;

@Repository
public class KeywordHotRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional
    public PagingResponse<KeywordHotEntity> getList(Integer pageIndex, Integer pageSize,String keyword, String platform, String category) {
        
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT SQL_CALC_FOUND_ROWS kw.* FROM bd_keyword_hot as kw");
        sb.append(" where kw.isDelete=0 ");

        List<Object> params = new ArrayList<>();
        if (StringUtils.isEmpty(keyword) == false) {
            sb.append(" AND kw.keyword = ?");
            params.add(keyword);
        }
        if (StringUtils.isEmpty(platform) == false) {
            sb.append(" AND kw.platform = ?");
            params.add(platform);
        }
        if (StringUtils.isEmpty(category) == false) {
            sb.append(" AND kw.category = ?");
            params.add(category);
        }
        

        sb.append(" ORDER BY kw.ranking ASC LIMIT ?,? ");
        params.add((pageIndex - 1) * pageSize);
        params.add(pageSize);

        List<KeywordHotEntity> list = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(KeywordHotEntity.class), params.toArray(new Object[params.size()]));
        Integer totalSize = getTotalSize();
        return new PagingResponse<>(pageIndex, pageSize, totalSize, list);
    }

  
    protected int getTotalSize() {
        return jdbcTemplate.queryForObject("SELECT FOUND_ROWS() as row_num;", int.class);
    }

    public void add(KeywordHotEntity entity){
        String sql = "INSERT INTO bd_keyword_hot (parentId,category,platform,keyword,ranking,goodsCount,sousuorenqi,sousuoredu,dianjirenqi,dianjiredu,dianjilv,zhifulv,jingzhengzhishu,chengjiaozhishu,includeDate) ";
        sql += " VALUE (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        jdbcTemplate.update(sql, entity.getParentId(),entity.getCategory(),entity.getPlatform(),entity.getKeyword(),entity.getRanking()
        ,entity.getGoodsCount(),entity.getSousuorenqi(),entity.getSousuoredu(),entity.getDianjirenqi(),entity.getDianjiredu()
        ,entity.getDianjilv(),entity.getZhifulv(),entity.getJingzhengzhishu(),entity.getChengjiaozhishu(),entity.getIncludeDate());
    }
}
